package com.sskj.mine.asset;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.hey.lib.HeySpinner;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.asset.data.AddressBean;
import com.sskj.mine.asset.data.RechargeTypeBean;
import com.sskj.mine.asset.data.WithdrawConfigBean;
import com.sskj.mine.component.DaggerUserDataComponent;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/05/04
 */
@Route(path = RConfig.MINE_WITHDRAW)//提币
public class WithdrawActivity extends BaseActivity<WithdrawPresenter> {


    @BindView(R2.id.right_tv)
    TextView rightTv;
    @BindView(R2.id.select_coin)
    HeySpinner selectCoin;
    @BindView(R2.id.available_tv)
    TextView availableTv;
    @BindView(R2.id.address_edt)
    EditText addressEdt;
    @BindView(R2.id.num_edt)
    EditText numEdt;
    @BindView(R2.id.unit_tv)
    TextView unitTv;
    @BindView(R2.id.max_num_tv)
    TextView maxNumTv;
    @BindView(R2.id.password_edt)
    EditText passwordEdt;
    @BindView(R2.id.code_edt)
    EditText codeEdt;
    @BindView(R2.id.get_code_tv)
    TextView getCodeTv;
    @BindView(R2.id.address_img)
    ImageView addressImg;
    @BindView(R2.id.submit_btn)
    Button submitBtn;
    @BindView(R2.id.tvFee)
    TextView tvFee;
    @BindView(R2.id.tvAll)
    TextView tvAll;
    private Disposable typeDispo;
    private String pid;
    private String coinType;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private Disposable timeDis;
    private List<RechargeTypeBean> rechargeTypeBeans;
    private RechargeTypeBean rechargeTypeBean;
    private BottomSheetDialog bottomSheetCoin;

    @Override
    public int getLayoutId() {
        return R.layout.mine_activity_withdraw;
    }

    @Override
    public WithdrawPresenter getPresenter() {
        return new WithdrawPresenter();
    }

    @Override
    public void initView() {
        setTitle(App.INSTANCE.getString(R.string.mine_assetRecordsActivity2_j));
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        selectCoin.setItemGravity(Gravity.CENTER);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
//            availableTv.setText(String.format("%s USDT", ""));

        });
        rightTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.mine_icon_history, 0);
        rightTv.setVisibility(View.VISIBLE);

    }

    @Override
    public void initData() {
        mPresenter.getType();
    }

    @Override
    protected void initEvent() {
        ClickUtil.click(rightTv, () -> ARouter.getInstance().build(RConfig.MINE_ASSET_RECORDS).withInt(Constans.TYPE, 0).navigation());

        ClickUtil.click(addressImg, () -> AddressListActivity.start(this));
        ClickUtil.click(getCodeTv, () -> {
            getCodeTv.setEnabled(false);
            String account = SPUtil.get(SPConfig.MOBILE, "");
            mPresenter.sendSms(account);
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddress(AddressBean addressBean) {
        if (addressEdt != null) {
            addressEdt.setText(addressBean.getAddress());
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, WithdrawActivity.class);
        context.startActivity(intent);
    }

    public void updateType(List<RechargeTypeBean> data) {

        if (data == null || data.size() <= 0) {
            return;
        }
        rechargeTypeBeans = data;
        pid = data.get(0).getPid();
        coinType = data.get(0).getPname();
        rechargeTypeBean = data.get(0);
        selectCoin.setText(coinType);
        refresh();
        typeDispo = Flowable.fromIterable(data)
                .map(RechargeTypeBean::getPname)
                .toList()
                .subscribe((strings, throwable) -> {
                    ClickUtil.click(selectCoin, () -> {
                        bottomSheetCoin = BottomSheetUtil.getBottomSheet(WithdrawActivity.this, null, (recyclerView, position, view) -> {
                            bottomSheetCoin.dismiss();
                            selectCoin.setText(strings.get(position));
                            pid = data.get(position).getPid();
                            coinType = data.get(position).getPname();
                            rechargeTypeBean = data.get(position);
                            refresh();
                        }, strings);
                        bottomSheetCoin.show();
                    });
//                    selectCoin.attachData(strings);
//                    selectCoin.setOnSelectListener(position -> {
//                        pid = data.get(position).getPid();
//                        coinType = data.get(position).getPname();
//                        rechargeTypeBean = data.get(position);
//                        refresh();
//                    });

                });
    }

    private void refresh() {
        WithdrawConfigBean withdrawConfigBean = new WithdrawConfigBean();
        withdrawConfigBean.setTb_fee(rechargeTypeBean.getTb_fee_rate());
        withdrawConfigBean.setTb_max(rechargeTypeBean.getTb_max());
        withdrawConfigBean.setTb_min(rechargeTypeBean.getTb_min());
        withdrawConfigBean.setUser_usable(rechargeTypeBean.getUsable());
        updateUI(withdrawConfigBean);
    }

    public void updateUI(WithdrawConfigBean data) {
        maxNumTv.setText("0");
        numEdt.setHint(String.format(App.INSTANCE.getString(R.string.mine_withdrawActivity2_j), data.getTb_min()));
        availableTv.setText(CoinUtil.keepCoinNumMax(coinType, data.getUser_usable()));
        tvFee.setText(String.format(App.INSTANCE.getString(R.string.mine_withdrawActivity3_j), data.getTb_fee(), coinType));
        ClickUtil.click(submitBtn, () -> {
            if (checkParam()) {
                mPresenter.withdraw(numEdt.getText().toString()
                        , pid, passwordEdt.getText().toString(),
                        codeEdt.getText().toString(),
                        addressEdt.getText().toString()
                );
            }
        });
        ClickUtil.click(tvAll, () -> {
            numEdt.setText(data.getUser_usable());
        });
        RxTextView.afterTextChangeEvents(numEdt)
                .subscribe(textViewAfterTextChangeEvent -> {
                    String s = textViewAfterTextChangeEvent.editable().toString();
                    if (TextUtils.isEmpty(s)) {
                        maxNumTv.setText("0");
                        return;
                    }
                    double v = Double.valueOf(s) - Double.valueOf(data.getTb_fee());
                    v = Math.max(0, v);

                    maxNumTv.setText(CoinUtil.keepCoinNumMax(coinType, v));
                });
    }

    private boolean checkParam() {

        if (TextUtils.isEmpty(addressEdt.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_addAddressActivity2_j));
            return false;
        }
        if (TextUtils.isEmpty(numEdt.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_withdrawActivity5_j));
            return false;
        }
        if (TextUtils.isEmpty(codeEdt.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_withdrawActivity6_j));
            return false;
        }
        if (TextUtils.isEmpty(passwordEdt.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_transferActivity4_j));
            return false;
        }
        return true;
    }

    public void sendCheckCodeSuccess() {
        DisposUtil.close(timeDis);
        timeDis = TimeUtil.newTime(this)
                .subscribe(aLong -> {
                    if (aLong > 0) {
                        getCodeTv.setText(aLong + "s");
                    } else {
                        getCodeTv.setText(App.INSTANCE.getString(R.string.mine_withdrawActivity8_j));
                        getCodeTv.setEnabled(true);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        DisposUtil.close(timeDis);
        super.onDestroy();
    }

    public void sendCheckCodeFail() {
        getCodeTv.setEnabled(true);
    }

    public void withdrawSuccess() {

    }
}
